package com.theory.sms.service.impl;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import com.theory.common.exception.Assert;
import com.theory.common.exception.BusinessException;
import com.theory.common.result.ResponseEnum;
import com.theory.sms.service.SmsService;
import com.theory.sms.util.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    /**
     * 批量发送短信的接口 给多个号码发送相同的验证码
     * @param templateID 模板id
     * @param phoneNumberSet 电话集合，可以输入多个
     * @param templateParamSet 模板里面的参数，即验证码，这个验证码不是电话有多少个就是多少个验证码，这个是模板里面的参数个数，一般就一个，所以这个方法可以给多个号码发送相同的验证码
     */
    @Override
    public void send(String templateID, String[] phoneNumberSet, String[] templateParamSet) {
        try{
        // 创建认证对象
        Credential credential = new Credential(SmsProperties.SECRET_ID, SmsProperties.SECRET_KEY);

        // 创建连接对象
        SmsClient smsClient = new SmsClient(credential, SmsProperties.REGION_ID);

        // 创建请求对象
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSmsSdkAppId(SmsProperties.APP_ID);
        sendSmsRequest.setSignName(SmsProperties.SIGN_NAME);
        sendSmsRequest.setTemplateId(templateID);
        sendSmsRequest.setPhoneNumberSet(phoneNumberSet);
        sendSmsRequest.setTemplateParamSet(templateParamSet);

        // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
        SendSmsResponse resp = smsClient.SendSms(sendSmsRequest);
        // 输出json格式的字符串回包
        System.out.println(SendSmsResponse.toJsonString(resp));

        for (SendStatus status : resp.getSendStatusSet()) {
            log.info("腾讯云短信发送响应结果：" + status.getMessage() + "，code：" + status.getCode());
            // 30秒只能发送1条
            Assert.notEquals("LimitExceeded.PhoneNumberThirtySecondLimit", status.getCode(), ResponseEnum.TENCENT_SMS_LIMIT_CONTROL_ERROR);
            // 状态码不是Ok，抛验证码发送失败
            Assert.equals("Ok", status.getCode(), ResponseEnum.TENCENT_SMS_ERROR);
        }

        } catch (TencentCloudSDKException e) {
            log.error("腾讯云短信发送失败");
            log.error("ErrorCode=" + e.getErrorCode());
            log.error("ErrorMessage=" + e.getMessage());
            throw new BusinessException(ResponseEnum.TENCENT_SMS_ERROR , e);
        }
    }
}
